// 获取DOM元素
const targetDateInput = document.getElementById('target-date');
const targetTimeInput = document.getElementById('target-time');
const eventNameInput = document.getElementById('event-name');
const startBtn = document.getElementById('start-btn');
const resetBtn = document.getElementById('reset-btn');
const countdownContainer = document.getElementById('countdown-container');
const eventTitle = document.getElementById('event-title');
const daysElement = document.getElementById('days');
const hoursElement = document.getElementById('hours');
const minutesElement = document.getElementById('minutes');
const secondsElement = document.getElementById('seconds');
const messageElement = document.getElementById('message');

// 设置默认日期为今天
const today = new Date();
const formattedDate = today.toISOString().split('T')[0];
targetDateInput.value = formattedDate;

// 设置默认时间为当前时间加1小时
const nextHour = new Date(today.getTime() + 60 * 60 * 1000);
const hours = nextHour.getHours().toString().padStart(2, '0');
const minutes = nextHour.getMinutes().toString().padStart(2, '0');
targetTimeInput.value = `${hours}:${minutes}`;

let countdownInterval;
let previousValues = { days: '00', hours: '00', minutes: '00', seconds: '00' };

// 开始倒计时函数
function startCountdown() {
    const dateValue = targetDateInput.value;
    const timeValue = targetTimeInput.value;
    const eventName = eventNameInput.value.trim() || '目标时间';
    
    if (!dateValue || !timeValue) {
        alert('请选择目标日期和时间！');
        return;
    }
    
    // 创建目标日期时间对象
    const targetDateTime = new Date(`${dateValue}T${timeValue}`);
    
    // 检查目标时间是否已过期
    if (targetDateTime <= new Date()) {
        alert('目标时间必须晚于当前时间！');
        return;
    }
    
    // 显示倒计时区域
    countdownContainer.classList.remove('hidden');
    eventTitle.textContent = eventName;
    
    // 清除之前的倒计时
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
    
    // 立即更新一次倒计时
    updateCountdown(targetDateTime, eventName);
    
    // 设置倒计时间隔（每秒更新一次）
    countdownInterval = setInterval(() => {
        updateCountdown(targetDateTime, eventName);
    }, 1000);
}

// 更新倒计时显示
function updateCountdown(targetDateTime, eventName) {
    const now = new Date();
    const timeDifference = targetDateTime - now;
    
    // 检查倒计时是否结束
    if (timeDifference <= 0) {
        clearInterval(countdownInterval);
        countdownContainer.classList.remove('hidden');
        eventTitle.textContent = eventName;
        daysElement.textContent = '00';
        hoursElement.textContent = '00';
        minutesElement.textContent = '00';
        secondsElement.textContent = '00';
        messageElement.textContent = `恭喜！${eventName} 已到达！`;
        
        // 添加动画效果
        document.querySelectorAll('.time-box').forEach(box => {
            box.classList.add('changed');
            setTimeout(() => box.classList.remove('changed'), 300);
        });
        
        return;
    }
    
    // 计算剩余时间（天、时、分、秒）
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
    
    // 格式化显示（两位数）
    const formattedDays = days.toString().padStart(2, '0');
    const formattedHours = hours.toString().padStart(2, '0');
    const formattedMinutes = minutes.toString().padStart(2, '0');
    const formattedSeconds = seconds.toString().padStart(2, '0');
    
    // 更新显示并添加动画效果
    if (formattedDays !== previousValues.days) {
        daysElement.textContent = formattedDays;
        daysElement.parentElement.classList.add('changed');
        setTimeout(() => daysElement.parentElement.classList.remove('changed'), 300);
        previousValues.days = formattedDays;
    }
    
    if (formattedHours !== previousValues.hours) {
        hoursElement.textContent = formattedHours;
        hoursElement.parentElement.classList.add('changed');
        setTimeout(() => hoursElement.parentElement.classList.remove('changed'), 300);
        previousValues.hours = formattedHours;
    }
    
    if (formattedMinutes !== previousValues.minutes) {
        minutesElement.textContent = formattedMinutes;
        minutesElement.parentElement.classList.add('changed');
        setTimeout(() => minutesElement.parentElement.classList.remove('changed'), 300);
        previousValues.minutes = formattedMinutes;
    }
    
    if (formattedSeconds !== previousValues.seconds) {
        secondsElement.textContent = formattedSeconds;
        secondsElement.parentElement.classList.add('changed');
        setTimeout(() => secondsElement.parentElement.classList.remove('changed'), 300);
        previousValues.seconds = formattedSeconds;
    }
    
    // 更新提示信息
    messageElement.textContent = `距离 ${eventName} 还有`;
}

// 重置函数
function resetCountdown() {
    // 清除倒计时间隔
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
    
    // 隐藏倒计时区域
    countdownContainer.classList.add('hidden');
    
    // 重置输入框
    eventNameInput.value = '';
    
    // 重置默认日期和时间
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    targetDateInput.value = formattedDate;
    
    const nextHour = new Date(today.getTime() + 60 * 60 * 1000);
    const hours = nextHour.getHours().toString().padStart(2, '0');
    const minutes = nextHour.getMinutes().toString().padStart(2, '0');
    targetTimeInput.value = `${hours}:${minutes}`;
    
    // 重置前一个值记录
    previousValues = { days: '00', hours: '00', minutes: '00', seconds: '00' };
}

// 添加事件监听器
startBtn.addEventListener('click', startCountdown);
resetBtn.addEventListener('click', resetCountdown);

// 监听键盘事件，按Enter键开始倒计时
document.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        startCountdown();
    }
});

// 添加页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 可以在这里添加额外的初始化逻辑
    console.log('仓颉倒数计时器已加载完成');
});